package com.lanou.zhihu.web.controller;

import com.lanou.zhihu.entity.Answer;
import com.lanou.zhihu.entity.User;
import com.lanou.zhihu.service.AnswerService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by QuChao on 2018/10/26.
 */
@Controller
@RequestMapping("/answer")
public class AnswerController {
    @Autowired
    private AnswerService answerService;

    @ResponseBody
    @RequestMapping("/add")
    public boolean answer(HttpServletRequest request, Answer answer) {
        if (!"".equals(answer.getContent()) && !"<p><br></p>".equals(answer.getContent()) && !answer.getContent().isEmpty()) {
            User user = (User) request.getSession().getAttribute("user");
            answer.setUid(user.getId());
            boolean result = answerService.addAnswer(answer);
            return result;
        } else {
            return false;
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public boolean delete(HttpServletRequest request, Integer id) {
        User user = (User) request.getSession().getAttribute("user");
        return answerService.delete(user.getId(), id);
    }

    @RequestMapping("/findAllByQid")
    @ResponseBody
    public Map<String, Object> findByQid(Integer qid) {
        Map<String, Object> map = new HashMap<>();
        List<Answer> answerList = answerService.findByQid(qid);
        map.put("rows", answerList);
        return map;
    }

    @ResponseBody
    @RequestMapping("/uploadImage")
    public String uploadImage(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String newName = new Date().getTime() + "AnswerModel.jpg";
        Client client = Client.create();
        String filePath = "http://47.106.73.53/zhihu/UserImage/" + newName;
        WebResource resource = client.resource(filePath);
        resource.put(inputStream);
        return filePath;
    }
}
